import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:dio/dio.dart'; // 添加Dio导入
import '../../core/offline/offline_data_manager.dart';
import '../../core/offline/offline_mode_manager.dart';
import '../../data/datasources/remote/note_api_service.dart';
import '../../data/datasources/remote/project_api_service.dart';
import '../../data/datasources/remote/todo_api_service.dart'
    as todo_api_service; // 添加待办API服务
import '../../data/models/note_model.dart' as note_model;
import '../../data/models/project_model.dart' as project_model;
import '../../data/models/todo_model.dart' as todo_model;

/// 离线同步服务
class OfflineSyncService {
  static final OfflineSyncService _instance = OfflineSyncService._internal();
  factory OfflineSyncService() => _instance;
  OfflineSyncService._internal();

  late NoteApiService _noteApiService;
  late ProjectApiService _projectApiService;
  late todo_api_service.TodoApiService _todoApiService; // 添加待办API服务
  late OfflineDataManager _offlineDataManager;
  late OfflineModeManager _offlineModeManager;

  bool _isInitialized = false;
  bool _isSyncing = false;

  /// 初始化服务
  Future<void> initialize({
    required NoteApiService noteApiService,
    required ProjectApiService projectApiService,
    required todo_api_service.TodoApiService todoApiService, // 添加待办API服务
    required OfflineDataManager offlineDataManager,
    required OfflineModeManager offlineModeManager,
  }) async {
    if (_isInitialized) return;

    _noteApiService = noteApiService;
    _projectApiService = projectApiService;
    _todoApiService = todoApiService; // 初始化待办API服务
    _offlineDataManager = offlineDataManager;
    _offlineModeManager = offlineModeManager;

    _isInitialized = true;
  }

  /// 同步所有离线操作
  Future<void> syncOfflineOperations() async {
    if (!_isInitialized || _isSyncing) return;

    _isSyncing = true;
    try {
      // 获取所有离线操作
      final operations = await _offlineDataManager.getOfflineOperations();

      if (operations.isEmpty) {
        _isSyncing = false;
        return;
      }

      final List<String> syncedOperationIds = [];

      // 按顺序处理每个操作
      for (final operation in operations) {
        try {
          switch (operation.operationType) {
            case OfflineOperationType.create:
              await _syncCreateOperation(operation);
              break;
            case OfflineOperationType.update:
              await _syncUpdateOperation(operation);
              break;
            case OfflineOperationType.delete:
              await _syncDeleteOperation(operation);
              break;
          }

          // 记录已同步的操作ID
          syncedOperationIds.add(operation.id);
        } on DioException catch (e) {
          debugPrint('同步离线操作失败，网络错误 (${operation.id}): $e');
          // 特别处理连接错误
          if (e.type == DioExceptionType.connectionError) {
            debugPrint('网络连接错误，请检查网络设置或稍后重试');
          }
          // 继续处理下一个操作，不中断整个同步过程
        } catch (e) {
          debugPrint('同步离线操作失败 (${operation.id}): $e');
          // 继续处理下一个操作，不中断整个同步过程
        }
      }

      // 删除已成功同步的操作记录
      if (syncedOperationIds.isNotEmpty) {
        await _offlineDataManager.removeSyncedOperations(syncedOperationIds);
      }
    } catch (e) {
      debugPrint('同步离线操作时发生错误: $e');
    } finally {
      _isSyncing = false;
    }
  }

  /// 同步创建操作
  Future<void> _syncCreateOperation(OfflineOperation operation) async {
    if (operation.entityType == 'note') {
      final request = note_model.NoteCreateRequest(
        title: operation.data['title'] as String,
        content: operation.data['content'] as String,
        noteType:
            note_model.NoteType.fromCode(operation.data['noteType'] as String),
        tags: List<String>.from(operation.data['tags'] as List),
        authorId: operation.data['authorId'] as int,
        isPublic: operation.data['isPublic'] as bool,
        projectId: operation.data['projectId'] as int?,
        todoId: operation.data['todoId'] as int?,
      );

      // 调用API创建笔记
      final response = await _noteApiService.createNote(request);

      if (!response.success) {
        throw Exception('创建笔记失败: ${response.message}');
      }
    } else if (operation.entityType == 'project') {
      final request = project_model.ProjectCreateRequest(
        projectName: operation.data['projectName'] as String,
        description: operation.data['description'] as String?,
        priority: project_model.Priority.fromCode(
            operation.data['priority'] as String),
        deadline: operation.data['deadline'] != null
            ? DateTime.parse(operation.data['deadline'] as String)
            : null,
      );

      // 调用API创建项目
      final response = await _projectApiService.createProject(request);

      if (!response.success) {
        throw Exception('创建项目失败: ${response.message}');
      }
    } else if (operation.entityType == 'todo') {
      final request = todo_model.TodoCreateRequest(
        projectId: operation.data['projectId'] as int,
        title: operation.data['title'] as String,
        description: operation.data['description'] as String?,
        priority:
            todo_model.Priority.fromCode(operation.data['priority'] as String),
        todoType:
            todo_model.TodoType.fromCode(operation.data['todoType'] as String),
        assigneeId: operation.data['assigneeId'] as int?,
        dueDate: operation.data['dueDate'] != null
            ? DateTime.parse(operation.data['dueDate'] as String)
            : null,
        estimatedHours: operation.data['estimatedHours'] as double?,
      );

      // 调用API创建待办
      final response = await _todoApiService.createTodo(request);

      if (!response.success) {
        throw Exception('创建待办失败: ${response.message}');
      }
    }
  }

  /// 同步更新操作
  Future<void> _syncUpdateOperation(OfflineOperation operation) async {
    if (operation.entityType == 'note') {
      final noteId = operation.data['id'] as int;

      final request = note_model.NoteUpdateRequest(
        title: operation.data['title'] as String?,
        content: operation.data['content'] as String?,
        noteType: operation.data['noteType'] != null
            ? note_model.NoteType.fromCode(operation.data['noteType'] as String)
            : null,
        tags: operation.data['tags'] != null
            ? List<String>.from(operation.data['tags'] as List)
            : null,
        isPublic: operation.data['isPublic'] as bool?,
      );

      // 调用API更新笔记
      final response = await _noteApiService.updateNote(noteId, request);

      if (!response.success) {
        throw Exception('更新笔记失败: ${response.message}');
      }
    } else if (operation.entityType == 'project') {
      final projectId = operation.data['id'] as int;

      final request = project_model.ProjectUpdateRequest(
        projectName: operation.data['projectName'] as String?,
        description: operation.data['description'] as String?,
        status: operation.data['status'] != null
            ? project_model.ProjectStatus.fromCode(
                operation.data['status'] as String)
            : null,
        priority: operation.data['priority'] != null
            ? project_model.Priority.fromCode(
                operation.data['priority'] as String)
            : null,
        deadline: operation.data['deadline'] != null
            ? DateTime.parse(operation.data['deadline'] as String)
            : null,
      );

      // 调用API更新项目
      final response =
          await _projectApiService.updateProject(projectId, request);

      if (!response.success) {
        throw Exception('更新项目失败: ${response.message}');
      }
    } else if (operation.entityType == 'todo') {
      final todoId = operation.data['id'] as int;

      final request = todo_model.TodoUpdateRequest(
        title: operation.data['title'] as String?,
        description: operation.data['description'] as String?,
        status: operation.data['status'] != null
            ? todo_model.TodoStatus.fromCode(operation.data['status'] as String)
            : null,
        priority: operation.data['priority'] != null
            ? todo_model.Priority.fromCode(operation.data['priority'] as String)
            : null,
        todoType: operation.data['todoType'] != null
            ? todo_model.TodoType.fromCode(operation.data['todoType'] as String)
            : null,
        assigneeId: operation.data['assigneeId'] as int?,
        dueDate: operation.data['dueDate'] != null
            ? DateTime.parse(operation.data['dueDate'] as String)
            : null,
        estimatedHours: operation.data['estimatedHours'] as double?,
        actualHours: operation.data['actualHours'] as double?,
      );

      // 调用API更新待办
      final response = await _todoApiService.updateTodo(todoId, request);

      if (!response.success) {
        throw Exception('更新待办失败: ${response.message}');
      }
    }
  }

  /// 同步删除操作
  Future<void> _syncDeleteOperation(OfflineOperation operation) async {
    if (operation.entityType == 'note') {
      final noteId = operation.data['id'] as int;

      // 调用API删除笔记
      final response = await _noteApiService.deleteNote(noteId);

      if (!response.success) {
        throw Exception('删除笔记失败: ${response.message}');
      }
    } else if (operation.entityType == 'project') {
      final projectId = operation.data['id'] as int;

      // 调用API删除项目
      final response = await _projectApiService.deleteProject(projectId);

      if (!response.success) {
        throw Exception('删除项目失败: ${response.message}');
      }
    } else if (operation.entityType == 'todo') {
      final todoId = operation.data['id'] as int;

      // 调用API删除待办
      final response = await _todoApiService.deleteTodo(todoId);

      if (!response.success) {
        throw Exception('删除待办失败: ${response.message}');
      }
    }
  }

  /// 检查是否有待同步的离线操作
  Future<bool> hasPendingOperations() async {
    final operations = await _offlineDataManager.getOfflineOperations();
    return operations.isNotEmpty;
  }
}
